#pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <jsoncpp/json/json.h>
#include <memory>
#include "LOG.hpp"
using namespace ns_LOG;
namespace ns_json
{
    class JsonUtil
    {
    public:
        // 序列化
        static bool serialize(const Json::Value val, std::string &out)
        {
            // 创建工厂
            Json::StreamWriterBuilder factory;
            factory["emitUTF8"] = true;
            std::stringstream ss;
            // 工厂创建对象
            std::unique_ptr<Json::StreamWriter> sw(factory.newStreamWriter());
            int r = sw->write(val, &ss);
            if (r != 0)
            {
                // std::cout << "Json serialize fail!!!" << std::endl;
                LOG(FATAL,"Json serialize fail!!!");
                return false;
            }
            out = ss.str();
            return true;
        }

        // 反序列化
        static bool unserialize(const std::string in, Json::Value &val)
        {
            // 创建工厂
            Json::CharReaderBuilder factory;

            // 工厂创建对象
            std::unique_ptr<Json::CharReader> cr(factory.newCharReader());

            std::string errs;
            int r = cr->parse(in.c_str(), in.c_str() + in.size(), &val, &errs);
            if (r == false)
            {
                //std::cout << "Json unserialize fail!!!" << std::endl;
                LOG(FATAL,"Json unserialize fail!!!");
                return false;
            }
            return true;
        }
    };
}